/*
 * Copyright (C) 2010 Patrick Gansterer <paroga@paroga.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "ChromeClientCd.h"
#include "Frame.h"
#include "FrameView.h"
#include "HitTestResult.h"
#include "FileChooser.h"
#include "ColorChooser.h"
#include "FileIconLoader.h"
#include "Icon.h"
#include "NotImplemented.h"
#include "NavigationAction.h"
#include "RenderTreeAsText.h"
#include "Page.h"
//#include "PopupMenuWin.h"
//#include "SearchPopupMenuWin.h"
#include "WebView.h"
#include <wtf/text/CString.h>
#include "WebKitLogging.h"

using namespace WebCore;

namespace WebKit {

ChromeClientCd::ChromeClientCd(WebView* webView)
    : m_webView(webView)
{
    ASSERT(m_webView);
}

void ChromeClientCd::chromeDestroyed(){
    delete this;
}

FloatRect ChromeClientCd::windowRect(){
    if (!m_webView)
        return FloatRect();

    IntRect rect;
    m_webView->frameRect(rect);
    return rect;
}

void ChromeClientCd::setWindowRect(const FloatRect&){
    notImplemented();
}

FloatRect ChromeClientCd::pageRect(){
    return windowRect();
}

void ChromeClientCd::focus(){
    notImplemented();
}

void ChromeClientCd::unfocus(){
    notImplemented();
}

Page* ChromeClientCd::createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, const NavigationAction&){
    notImplemented();
    LOG(ChromeClient,"ChromeClientCd::createWindow");
    return nullptr;
}

void ChromeClientCd::show(){
    notImplemented();
}

bool ChromeClientCd::canRunModal(){
    notImplemented();
    return false;
}

void ChromeClientCd::runModal(){
    notImplemented();
}

void ChromeClientCd::setToolbarsVisible(bool){
    notImplemented();
}

bool ChromeClientCd::toolbarsVisible(){
    return false;
}

void ChromeClientCd::setStatusbarVisible(bool){
    notImplemented();
}

bool ChromeClientCd::statusbarVisible(){
    notImplemented();
    return false;
}

void ChromeClientCd::setScrollbarsVisible(bool){
    notImplemented();
}

bool ChromeClientCd::scrollbarsVisible(){
    notImplemented();
    return false;
}

void ChromeClientCd::setMenubarVisible(bool){
    notImplemented();
}

bool ChromeClientCd::menubarVisible(){
    notImplemented();
    return false;
}

void ChromeClientCd::setResizable(bool){
    notImplemented();
}

void ChromeClientCd::closeWindowSoon(){
    notImplemented();
    //PostMessageW(m_webView->windowHandle(), WM_CLOSE, 0, 0);
}

bool ChromeClientCd::canTakeFocus(FocusDirection){
    return true;
}

void ChromeClientCd::takeFocus(FocusDirection){
    unfocus();
}

void ChromeClientCd::focusedElementChanged(WebCore::Element*){
    notImplemented();
}

void ChromeClientCd::focusedFrameChanged(WebCore::Frame*){
}

bool ChromeClientCd::canRunBeforeUnloadConfirmPanel(){
    return true;
}

bool ChromeClientCd::runBeforeUnloadConfirmPanel(const String& message, WebCore::Frame* frame){
    return runJavaScriptConfirm(frame, message);
}

void ChromeClientCd::addMessageToConsole(MessageSource, MessageLevel, const String&msg, unsigned line, unsigned colume, const String&source){
    //LOG(ChromeClient,"[%s:%d]:%s\r\n",source.utf8().data(),line,msg.utf8().data());
}

void ChromeClientCd::runJavaScriptAlert(WebCore::Frame*, const String& message){
    m_webView->runJavaScriptAlert(message);
}

bool ChromeClientCd::runJavaScriptConfirm(WebCore::Frame*, const String& message){
    return m_webView->runJavaScriptConfirm(message);
}

bool ChromeClientCd::runJavaScriptPrompt(WebCore::Frame*, const String& message, const String& defaultValue, String& result){
    return m_webView->runJavaScriptPrompt(message, defaultValue, result);
}

void ChromeClientCd::setStatusbarText(const String&text){
    LOG(ChromeClient,"%s",text.utf8().data());
}

bool ChromeClientCd::shouldInterruptJavaScript(){
    notImplemented();
    return false;
}

KeyboardUIMode ChromeClientCd::keyboardUIMode(){
    return KeyboardAccessTabsToLinks;
}

IntRect ChromeClientCd::windowResizerRect() const{
    notImplemented();
    return IntRect();
}

void ChromeClientCd::invalidateRootView(const IntRect&rect){
    LOG(ChromeClient,"ChromeClientCd::invalidateRootView");
    m_webView->invalidate(rect.x(),rect.y(),rect.width(),rect.height());
}

void ChromeClientCd::invalidateContentsAndRootView(const IntRect& updateRect){
#if USE(ACCELERATED_COMPOSITING)
    AcceleratedCompositingContext* acContext = m_webView->priv->acceleratedCompositingContext.get();
    if (acContext->enabled()) {
        acContext->setNonCompositedContentsNeedDisplay(updateRect);
        return;
    }
#endif
    if (updateRect.isEmpty())
        return;
    m_dirtyRegion.unite(updateRect);    
    //LOG(ChromeClient,"ChromeClientCd::invalidateContentsAndRootView(%d,%d,%d,%d)",
    //   updateRect.x(),updateRect.y(),updateRect.width(),updateRect.height());    
    m_webView->invalidate(updateRect.x(),updateRect.y(),updateRect.width(),updateRect.height());
    //m_displayTimer.startOneShot(0);
}

void ChromeClientCd::invalidateContentsForSlowScroll(const IntRect& updateRect)
{
#if USE(ACCELERATED_COMPOSITING)
    AcceleratedCompositingContext* acContext = m_webView->priv->acceleratedCompositingContext.get();
    if (acContext->enabled()) {
        acContext->setNonCompositedContentsNeedDisplay(updateRect);
        return;
    }
#endif	
    invalidateContentsAndRootView(updateRect);
}

void ChromeClientCd::scroll(const IntSize&delta, const IntRect& rectToScroll, const IntRect&clipRect)
{
    m_rectsToScroll.append(rectToScroll);
    m_scrollOffsets.append(delta);
    // The code to calculate the scroll repaint region is originally from WebKit2.
    // Get the part of the dirty region that is in the scroll rect.
    WebCore::Region dirtyRegionInScrollRect = intersect(rectToScroll, m_dirtyRegion);
    if (!dirtyRegionInScrollRect.isEmpty()) {
        // There are parts of the dirty region that are inside the scroll rect.
        // We need to subtract them from the region, move them and re-add them.
        m_dirtyRegion.subtract(rectToScroll);
        // Move the dirty parts.
	WebCore::Region movedDirtyRegionInScrollRect = intersect(translate(dirtyRegionInScrollRect, delta), rectToScroll);
        // And add them back.
        m_dirtyRegion.unite(movedDirtyRegionInScrollRect);
    }
    // Compute the scroll repaint region. We ensure that we are not subtracting areas
    // that we've scrolled from outside the viewport from the repaint region.
    IntRect onScreenScrollRect = rectToScroll;
    onScreenScrollRect.intersect(IntRect(IntPoint(), enclosingIntRect(pageRect()).size()));
    Region scrollRepaintRegion = subtract(rectToScroll, translate(onScreenScrollRect, delta));

    m_dirtyRegion.unite(scrollRepaintRegion);
    //m_displayTimer.startOneShot(0); 
    //invalidateContentsAndRootView(rectToScroll);
    LOG(ChromeClient,"ChromeClientCd::scroll delta=%dx%d rectToScroll=(%d,%d-%d,%d)",delta.width(),delta.height(),rectToScroll.x(),rectToScroll.y(),
		    rectToScroll.width(),rectToScroll.height());
}

IntRect ChromeClientCd::rootViewToScreen(const IntRect& rect) const
{
    notImplemented();
    return rect;
}

IntPoint ChromeClientCd::screenToRootView(const IntPoint& point) const
{
    notImplemented();
    //IntPoint widgetPositionOnScreen = convertWidgetPointToScreenPoint(GTK_WIDGET(m_webView), IntPoint());
    IntPoint result(point);
    //result.move(-widgetPositionOnScreen.x(), -widgetPositionOnScreen.y());
    return result;    
}

PlatformPageClient ChromeClientCd::platformPageClient() const
{
    notImplemented();
    return m_webView;
}

void ChromeClientCd::contentsSizeChanged(Frame*frame, const IntSize&size) const
{
    //LOG(WebView,"ChromeClientCd::contentsSizeChanged frame=%p:%d size(%dx%d)",frame,frame->isMainFrame(),size.width(),size.height());
    if(frame && frame==(WebCore::Frame*)&m_webView->page()->mainFrame())
	m_webView->setContentSize(size.width(),size.height());
}

void ChromeClientCd::scrollbarsModeDidChange() const
{
    notImplemented();
}

void ChromeClientCd::mouseDidMoveOverElement(const HitTestResult&hit, unsigned modifierFlags)
{
    bool isLink = hit.isLiveLink();
    if (isLink) {
        URL url = hit.absoluteLinkURL();
        if (!url.isEmpty() && url != m_hoveredLinkURL) {
            TextDirection dir;
            CString titleString = hit.title(dir).utf8();
            CString urlString = url.string().utf8();
            //g_signal_emit_by_name(m_webView, "hovering-over-link", titleString.data(), urlString.data());
            m_hoveredLinkURL = url;
        }
    } else if (!isLink && !m_hoveredLinkURL.isEmpty()) {
        //g_signal_emit_by_name(m_webView, "hovering-over-link", 0, 0);
        m_hoveredLinkURL = URL();
    }

    if (Node* node = hit.innerNonSharedNode()) {
        Frame* frame = node->document().frame();
        FrameView* view = frame ? frame->view() : 0;
        m_webView->setToolTipArea( view ? view->contentsToWindow(node->pixelSnappedBoundingBox()) : IntRect());
    } else{
        m_webView->setToolTipArea(IntRect());
    }
}

void ChromeClientCd::setToolTip(const String&toolTip, TextDirection){
    m_webView->setToolTip(toolTip);
}

void ChromeClientCd::print(Frame*)
{
    notImplemented();
}

#if ENABLE(SQL_DATABASE)
void ChromeClientCd::exceededDatabaseQuota(Frame*frame, const String&databaseName, DatabaseDetails)
{
    notImplemented();
    /*DatabaseManager::manager().setQuota(frame->document()->securityOrigin(), defaultQuota);

    WebKitWebFrame* webFrame = kit(frame);
    WebKitSecurityOrigin* origin = webkit_web_frame_get_security_origin(webFrame);
    WebKitWebDatabase* webDatabase = webkit_security_origin_get_web_database(origin, databaseName.utf8().data());
    g_signal_emit_by_name(m_webView, "database-quota-exceeded", webFrame, webDatabase);
    */
}
#endif

void ChromeClientCd::reachedMaxAppCacheSize(int64_t)
{
    notImplemented();
}

void ChromeClientCd::reachedApplicationCacheOriginQuota(SecurityOrigin*, int64_t)
{
    notImplemented();
}

#if ENABLE(TOUCH_EVENTS)
void ChromeClientCd::needTouchEvents(bool need)
{
    notImplemented();
    //LOG(ChromeClient,"ChromeClientCd::needTouchEvents(%d)",need);
}
#endif

void ChromeClientCd::attachRootGraphicsLayer(Frame*, GraphicsLayer*)
{
    notImplemented();
}

void ChromeClientCd::setNeedsOneShotDrawingSynchronization()
{
    notImplemented();
}

void ChromeClientCd::scheduleCompositingLayerFlush()
{
    notImplemented();
#if USE(ACCELERATED_COMPOSITING)    
    m_webView->compositor().scheduleLayerFlush(false);
#endif    
}

#if ENABLE(INPUT_TYPE_COLOR)
PassOwnPtr<WebCore::ColorChooser> ChromeClientCd::createColorChooser(ColorChooserClient*, const WebCore::Color&){
    notImplemented();
    return nullptr;
}
#endif

void ChromeClientCd::runOpenPanel(Frame*, PassRefPtr<FileChooser> prpFileChooser)
{
    notImplemented();
}

void ChromeClientCd::loadIconForFiles(const Vector<String>& filenames, FileIconLoader* loader)
{
    loader->notifyFinished(Icon::createIconForFiles(filenames));
}

void ChromeClientCd::setCursor(const Cursor&)
{
    notImplemented();
}

void ChromeClientCd::setCursorHiddenUntilMouseMoves(bool)
{
    notImplemented();
}

#if ENABLE(REQUEST_ANIMATION_FRAME) && !USE(REQUEST_ANIMATION_FRAME_TIMER)
void ChromeClientCd::scheduleAnimation(){
    notImplemented();
}
#endif

void ChromeClientCd::setLastSetCursorToCurrentCursor()
{
    notImplemented();
}

void ChromeClientCd::AXStartFrameLoad()
{
    notImplemented();
}

void ChromeClientCd::AXFinishFrameLoad()
{
    notImplemented();
}

bool ChromeClientCd::selectItemWritingDirectionIsNatural()
{
    return false;
}

bool ChromeClientCd::selectItemAlignmentFollowsMenuWritingDirection()
{
    return false;
}

bool ChromeClientCd::hasOpenedPopup() const
{
    notImplemented();
    return false;
}

PassRefPtr<PopupMenu> ChromeClientCd::createPopupMenu(PopupMenuClient* client) const
{
    return nullptr;//adoptRef(new PopupMenuWin(client));
}

PassRefPtr<SearchPopupMenu> ChromeClientCd::createSearchPopupMenu(PopupMenuClient* client) const
{
    return nullptr;//adoptRef(new SearchPopupMenuWin(client));
}

} // namespace WebKit
